package com.pospi.pai.yunpos.report;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.maning.library.MClearEditText;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.callbacklistener.HttpCallBackListener;
import com.pospi.http.HttpConnection;
import com.pospi.pai.yunpos.R;
import com.pospi.pai.yunpos.base.Base2Activity;
import com.pospi.pai.yunpos.been.SupBeen;
import com.pospi.pai.yunpos.caigou.SupActivity;
import com.pospi.pai.yunpos.login.Constant;
import com.pospi.pai.yunpos.util.BillUtil;


import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

//库存查询

public class InventorySearchActivity extends Base2Activity {
    @Bind(R.id.et_search)
    MClearEditText et_search;
    @Bind(R.id.ll_title)
    LinearLayout ll_title;
    @Bind(R.id.kc_list)
    ListView kc_list;
    @Bind(R.id.tv_zkcsl)
    TextView tv_zkcsl;
    @Bind(R.id.tv_zkcje)
    TextView tv_zkcje;

    @Bind(R.id.tv_fl)
    TextView tv_fl;
    @Bind(R.id.tv_md)
    TextView tv_md;
    @Bind(R.id.tv_gys)
    TextView tv_gys;
    @Bind(R.id.tv_pp)
    TextView tv_pp;
    @Bind(R.id.tv_up)
    TextView tv_up;
    @Bind(R.id.tv_page)
    TextView tv_page;
    @Bind(R.id.tv_next)
    TextView tv_next;
    @Bind(R.id.tv_total)
    TextView tv_total;





    private List<KcBill> kcBills = new ArrayList<>();
    private MyAdapter adapter;
    private String count;
    private String je;
    private int page = 1;
    private int pages = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_inventory_list);
        ButterKnife.bind(this);
        setTitle("库存查询");
//        ll_title.setVisibility(View.GONE);
        setMenuImage(R.drawable.icon_search_white);
        down();
        downpp();
        downmd();
        adapter = new MyAdapter();
        kc_list.setAdapter(adapter);
        tv_up.setVisibility(View.INVISIBLE);

    }

    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        startActivity(InventorySearchDetailActivity.class);
    }

    private List<SupBeen> fl_Beens = new ArrayList<>();//分类
    private List<SupBeen> pp_Beens = new ArrayList<>();//品牌
    private List<SupBeen> md_Beens = new ArrayList<>();//门店
    private String market = "";
    private String cat = "";
    private String brand = "";
    private String supid = "";

    private void creatDialogCat(final List<String> ss) {

        new CircleDialog.Builder(this)
                .setItems(ss, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        //分类

                        tv_fl.setText(ss.get(i));
                        cat = fl_Beens.get(i).getId();


                    }
                })
                .setGravity(Gravity.CENTER_VERTICAL)
                .setWidth(0.5f)
                .show();
    }

    private void creatDialogBrand(final List<String> ss) {

        new CircleDialog.Builder(this)
                .setItems(ss, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        //品牌

                        tv_pp.setText(ss.get(i));
                        brand = pp_Beens.get(i).getId();


                    }
                })
                .setGravity(Gravity.CENTER_VERTICAL)
                .setWidth(0.5f)
                .show();
    }

    private void creatDialogMarket(final List<String> ss) {

        new CircleDialog.Builder(this)
                .setItems(ss, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        //门店

                        tv_md.setText(ss.get(i));
                        market = md_Beens.get(i).getId();


                    }
                })
                .setGravity(Gravity.CENTER_VERTICAL)
                .setWidth(0.5f)
                .show();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        SupBeen been = (SupBeen) intent.getSerializableExtra("sup");
        if (been != null) {
            tv_gys.setText(been.getName());
            supid = been.getId();
        }

    }

    List<String> strings = new ArrayList<>();

    @OnClick({R.id.iv_search_xz, R.id.tv_fl, R.id.tv_pp, R.id.tv_md, R.id.tv_gys, R.id.bt_search,
            R.id.tv_up, R.id.tv_next})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_up://上一页
                if (page > 1) {
                    page--;
                    searchBill("ss",page , 20);
                    tv_page.setText(String.valueOf(page));
                    if (page == 1) {
                        tv_up.setVisibility(View.INVISIBLE);
                    }

                }

                break;
            case R.id.tv_next://下一页
                if (page < pages) {
                    page++;
                    searchBill("ss",page , 20);
                }

                tv_page.setText(String.valueOf(page));
                tv_up.setVisibility(View.VISIBLE);
                break;
            case R.id.iv_search_xz://搜索
                searchBill("ss",1 , 20);
                break;
            case R.id.tv_fl:
              showfl(tv_fl);

                break;
            case R.id.tv_pp:
                showpp(tv_pp);
                break;
            case R.id.tv_md:
              showmd(tv_md);
                break;
            case R.id.tv_gys:
                Intent intent = new Intent(this, SupActivity.class);
                intent.putExtra("mark", "InventorySearchDetailActivity");
                startActivity(intent);
                break;
            case R.id.bt_search:
                searchBill("",1 ,20);
                break;
        }
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return kcBills.size();
        }

        @Override
        public Object getItem(int i) {
            return kcBills.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder;
            if (view == null) {
                holder = new Holder();
                view = LayoutInflater.from(InventorySearchActivity.this).inflate(R.layout.kc_bill_item, null);
                holder.name = view.findViewById(R.id.name);
                holder.tv_jj = view.findViewById(R.id.tv_jj);
                holder.tv_lsj = view.findViewById(R.id.tv_lsj);
                holder.tv_pfj = view.findViewById(R.id.tv_pfj);
                holder.tv_sl = view.findViewById(R.id.tv_sl);
                holder.tv_js = view.findViewById(R.id.tv_js);
                holder.tv_kcje = view.findViewById(R.id.tv_kcje);
                holder.code = view.findViewById(R.id.code);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }
            KcBill bill = kcBills.get(i);
            holder.name.setText(bill.getName());
            holder.code.setText(bill.getBarcode());
            holder.tv_jj.setText(bill.getJj());
            holder.tv_lsj.setText(bill.getLsj());
            holder.tv_pfj.setText(bill.getPfj());
            holder.tv_sl.setText(bill.getKcsl());
            holder.tv_js.setText(bill.getKcjs());
            holder.tv_kcje.setText(bill.getJjje());
            return view;
        }

        class Holder {
            TextView name;
            TextView tv_jj;
            TextView tv_lsj;
            TextView tv_pfj;
            TextView tv_sl;
            TextView tv_js;
            TextView tv_kcje;
            TextView code;

        }
    }

    List<KcBill> bills = new ArrayList<>();

    private void searchBill(String type,int page ,int limit) {
        bills.clear();
        showLodingDialog();
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "report.mkcbb");
        params.put("fun", "find_spkchz");

        params.put("page", String.valueOf(page));
        params.put("limit", String.valueOf(limit));


        JSONObject object = new JSONObject();
        try {
            if (type.equals("ss")) {
                object.put("filter", et_search.getText().toString().trim());
            } else {
                object.put("catid", cat);
                object.put("market", market);
                object.put("brandid", brand);
                object.put("supid", supid);
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("login", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    Log.i("login", jsonObject.getString("errMsg"));
                    count = jsonObject.getString("count");
                    je = jsonObject.getJSONObject("sumrow").getString("jjje");
                    if (result.length() > 1) {
                        for (int j = 0; j < result.length() - 1; j++) {
                            JSONObject data = result.getJSONObject(j);
                            KcBill kcBill = new KcBill();
                            kcBill.setName(data.getString("name"));
                            kcBill.setBarcode(data.getString("barcode"));
                            kcBill.setJj(data.getString("jj"));
                            kcBill.setLsj(data.getString("lsj"));
                            kcBill.setPfj(data.getString("pfj"));

                            kcBill.setKcsl(data.getString("kcsl"));
                            kcBill.setKcjs(data.getString("kcjs"));
                            kcBill.setJjje(data.getString("jjje"));
                            bills.add(kcBill);
                        }
                    }
                    Message message = Message.obtain();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        });

    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    closeLodindDialog();

                    if (bills.size() > 0) {
                        kcBills.clear();
                        kcBills.addAll(bills);
                        ll_title.setVisibility(View.VISIBLE);
                        tv_zkcsl.setText(count);
                        tv_zkcje.setText(je);
                        pages = (int) Double.parseDouble(count) / 20;
                        tv_total.setText("共"+ pages +"页");
                    } else {
//                        ll_title.setVisibility(View.GONE);
                        Toast.makeText(InventorySearchActivity.this, "暂时没有了", Toast.LENGTH_SHORT).show();
                    }
                    adapter.notifyDataSetChanged();
                    break;
            }

        }
    };

    //下载分类
    private void down() {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastgoodscat");
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    fl_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SupBeen>>() {
                    }.getType());
                    fl_Beens.add(new BillUtil().getNewSup());
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        });


    }

    //下载
    private void downmd() {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastmarket");
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    md_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SupBeen>>() {
                    }.getType());
                    md_Beens.add(new BillUtil().getNewSup());
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        });


    }

    //下载
    private void downpp() {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastgoodsbrand");
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    pp_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SupBeen>>() {
                    }.getType());
                    pp_Beens.add(new BillUtil().getNewSup());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }
        });
    }

    private void showmd(View v) {
        List<String> strings = new ArrayList<>();
        strings.clear();
        for (SupBeen been : md_Beens) {
            strings.add(been.getName());
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_yyy, null);
        final PopupWindow yyyPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        yyyPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        yyyPopupWindow.setFocusable(true);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int height = contentView.getMeasuredHeight();
        int width = contentView.getMeasuredWidth();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
//        yyyPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - width / 2, location[1]);
        yyyPopupWindow.showAsDropDown(v);

        ListView listView = contentView.findViewById(R.id.yyy_list);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv_md.setText(md_Beens.get(position).getName());
                market = md_Beens.get(position).getId();
                yyyPopupWindow.dismiss();
            }
        });
    }

    private void showfl(View v) {
        List<String> strings = new ArrayList<>();
        strings.clear();
        for (SupBeen been : fl_Beens) {
            strings.add(been.getName());
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_yyy, null);
        final PopupWindow yyyPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        yyyPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        yyyPopupWindow.setFocusable(true);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int height = contentView.getMeasuredHeight();
        int width = contentView.getMeasuredWidth();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
//        yyyPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - width / 2, location[1]);
        yyyPopupWindow.showAsDropDown(v);

        ListView listView = contentView.findViewById(R.id.yyy_list);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv_fl.setText(fl_Beens.get(position).getName());
                cat = fl_Beens.get(position).getId();
                yyyPopupWindow.dismiss();
            }
        });
    }

    private void showpp(View v) {
        List<String> strings = new ArrayList<>();
        strings.clear();
        for (SupBeen been : pp_Beens) {
            strings.add(been.getName());
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_yyy, null);
        final PopupWindow yyyPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        yyyPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        yyyPopupWindow.setFocusable(true);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int height = contentView.getMeasuredHeight();
        int width = contentView.getMeasuredWidth();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
//        yyyPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - width / 2, location[1]);
        yyyPopupWindow.showAsDropDown(v);

        ListView listView = contentView.findViewById(R.id.yyy_list);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv_pp.setText(pp_Beens.get(position).getName());
                brand = pp_Beens.get(position).getId();
                yyyPopupWindow.dismiss();
            }
        });
    }

}
